package servidorIndice.ui;

import servidorIndice.controlador.Registro;
import servidorIndice.controlador.ServidorIndice;
import servidorIndice.controlador.RegistrosControlador;
import java.util.ArrayList;

/*
 * ServidorFrame.java
 * Clase de tipo JFrame que permite manipula la interface de ususario
 * esta clase es elaborada sobre la plataforma NetBeans
 *
 * @author Jorge Hernán Londoño Echeverri narzyx@gmail.com Hayner Benavides Moreno hayner2005@gmail.com
 */
public class ServidorFrame extends javax.swing.JFrame {

    //private java.util.ArrayList<ProcesarServidorIndice> listaProcesos;
    private ServidorIndice servidor;

    /** Creates new form ServidorFrame */
    public ServidorFrame() {
        super("Servidor Indice");
        initComponents();        
        setVisible(true);
        establecerConexion();
      //  listaProcesos = new ArrayList<ProcesarServidorIndice>();
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        bitacora = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Indice", "IP", "Puerto", "Estado"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setName("listadoConexiones"); // NOI18N
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(0).setHeaderValue("Indice");
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setHeaderValue("IP");
        jTable1.getColumnModel().getColumn(2).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(2).setHeaderValue("Puerto");
        jTable1.getColumnModel().getColumn(3).setResizable(false);
        jTable1.getColumnModel().getColumn(3).setHeaderValue("Estado");

        jButton1.setText("Desconectar");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Actualizar");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });

        bitacora.setColumns(20);
        bitacora.setRows(5);
        jScrollPane2.setViewportView(bitacora);

        jLabel1.setText("Bitácora");

        jLabel2.setText("Clientes conectados");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
        refrescar();
    }//GEN-LAST:event_jButton2MouseClicked
    /**
     * Método de tipo evento que permite desconectar
     * y cerrar el registro controlador, para eliminar
     * el socket que se ecnuentra abierto, de pendiendo
     * del registro seleccionado dentro de la lista
     * de clientes seleccionados
     * @param evt
     */
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
       

    }//GEN-LAST:event_jButton1ActionPerformed
    /**
     * Método que de tipo evento que limpia la bitacora
     * del Frame
     * @param evt
     */
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
         try{
            int filaSelecccionada=jTable1.getSelectedRow();
            if(filaSelecccionada != -1){
                int indice=Integer.parseInt(jTable1.getValueAt(filaSelecccionada, 0).toString());
                ArrayList<Registro> lista = new ArrayList<Registro>();

                RegistrosControlador controlador = new RegistrosControlador();
                if(controlador.init("sqlite")){
                    lista=controlador.buscar();
                }
                controlador.cerrar();
                for(int i = 0; i < lista.size(); i++) {
                    if(lista.get(i).getIndice().equals(indice+"")){
                        javax.swing.table.DefaultTableModel modelo = (javax.swing.table.DefaultTableModel) jTable1.getModel();
                        modelo.removeRow(filaSelecccionada);
                        servidor.eliminarProceso(Integer.parseInt(lista.get(i).getIndice()));
                        //this.bitacora.setText(this.bitacora.getText()+"Se ha desconectado el cliente con indice: "+lista.get(i).getIndice()+" e IP: "+lista.get(i).getIp()+"\n");
                        //System.out.println("proceso "+listaProcesos.get(i).getRegistro().getIp());
                    }
                }
                refrescar();
            }
        }
        catch(Exception e){
            e.printStackTrace();
            System.out.println("ocurrio un error al convertir ");
        }
    }//GEN-LAST:event_jButton1MouseClicked

    /**
    * Método principal
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ServidorFrame();                
            }
        });
    }
    /**
     * Método que inicia la conecxión del servidor de
     * indices
     */
    public void establecerConexion(){
        try {
            servidor= new ServidorIndice();
            servidor.start();

        } catch (Exception e) {
           //  System.out.println("se ha producido un error de conexión");
             this.bitacora.setText(this.bitacora.getText()+"Se ha producido un error de conexión\n");
        }       
    }
    /**
     * Método que refresca la tabla de clientes
     * que se ha conectado
     */
    public void refrescar(){
        RegistrosControlador controlador = new RegistrosControlador();
        ArrayList<Registro> listaProcesos= new ArrayList<Registro>();
        if(controlador.init("sqlite")){
            listaProcesos = controlador.buscar();
        }
        controlador.cerrar();
        limpiar();
       
        for(Registro registro : listaProcesos){
            //this.bitacora.setText(this.bitacora.getText()+"Se ha conectado un nuevo cliente con IP: "+registro.getIp()+"\n");
            insertar(registro);            
        }

        ArrayList<String> bitacora = servidor.getBitacoraClientes();
        this.bitacora.setText("");
        for(String anotacion : bitacora){
            this.bitacora.setText(this.bitacora.getText()+"\r\n "+anotacion);
        }
    }
    /**
     * Método que inbresa un nuevo cliente a la tabla
     * de detalle de conectados
     * @param registro
     */
    public void insertar(Registro registro){
        javax.swing.table.DefaultTableModel modelo = (javax.swing.table.DefaultTableModel) jTable1.getModel();
        Object[] fila = {registro.getIndice(),registro.getIp(),registro.getPuerto(),"Conectado"};        
        modelo.addRow(fila);
    }

    public void limpiar(){
        javax.swing.table.DefaultTableModel modelo = (javax.swing.table.DefaultTableModel)jTable1.getModel();       
        while (modelo.getRowCount()>0){
            modelo.removeRow(0);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea bitacora;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

}
